package com.choudou5.utils;

import cn.hutool.core.collection.CollUtil;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 配置文件工具类
 * @author xuhaowende@sina.cn
 * @time 2019-08-15
 */
public class ConfigUtil {

    private static Map<String, String> props = new ConcurrentHashMap();

    static {
        refresh();
    }

    //获取配置
    public static String get(String key){
        return props.get(key);
    }

    //刷新配置
    public static void refresh(){
        LogUtil.debug("开始刷新属性配置");
        InputStream is = null;
        String path = ConfigUtil.class.getClassLoader().getResource("application.properties").getPath();
        try {
            is = new FileInputStream(path);
            Properties prop = new Properties();
            prop.load(is);
            Set<Object> keys = prop.keySet();
            if(CollUtil.isNotEmpty(keys)){
                for (Object key : keys) {
                    props.put(key.toString(), prop.getProperty(key.toString()));
                }
            }
        } catch (IOException e) {
            LogUtil.error("加载application.properties失败", e);
        }finally {
            try {
                if(is != null) is.close();
            } catch (IOException e) {
                LogUtil.error("关闭文件流失败", e);
            }
        }
    }

//        ResourceBundle resource = ResourceBundle.getBundle("application");
//        Enumeration<String> keys = resource.getKeys();
//        if(CollUtil.isNotEmpty(keys)){
//            while (keys.hasMoreElements()){
//                String key = keys.nextElement();
//                props.put(key, resource.getString(key));
//            }
//        }

}
